package com.zzy.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzy.common.core.domain.AjaxResult;
import com.zzy.common.core.domain.entity.SysUser;
import com.zzy.common.core.page.TableDataInfo;
import com.zzy.common.core.redis.RedisCache;
import com.zzy.common.utils.guanmai.GuanmaiCommon;
import com.zzy.system.domain.GuanmaiSpu;
import com.zzy.system.domain.SkuStock;
import com.zzy.system.mapper.GuanmaiSpuMapper;
import com.zzy.system.mapper.SkuStockMapper;
import com.zzy.system.service.ISkuStockService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {
    private static final Logger log = LoggerFactory.getLogger(SkuStockServiceImpl.class);

    // 注入 RedisCache 对象
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SkuStockMapper skuStockMapper;

    @Override
    public String getGuanmaiSkuStock(Integer status, String startDate, String endDate, Integer offset, Integer limit, Integer queryType) throws Exception {
        List<SkuStock> allSkuStockList = new ArrayList<>();
        offset=0;
        limit=100;
        while (true) {
            Map<String, Object> paramMap = new HashMap<>();
            // 设置分页offset参数（默认值为0，可按需不传该参数或者修改值）
            paramMap.put("offset", offset);
            // 设置分页limit参数（默认值为100，取值范围<=100，可按需不传该参数或者修改值）
            paramMap.put("limit", limit);

            //请求观麦 获取订单列表
            String reponse = GuanmaiCommon.sendRequestGet(paramMap, "/v1/api/stock/list/1.0");
            JSONObject reponseJson = JSONObject.parseObject(reponse);
            if (reponseJson.getInteger("code") == 1002) {
                GuanmaiCommon.getGuanmaiToken();
                continue;
            }
            if (reponseJson.get("code").toString().equals("0")) {
                JSONArray jsonArray = reponseJson.getJSONArray("data");
                if (jsonArray != null) {
                    // 将当前页的数据解析并添加到总的结果列表中
                    List<SkuStock> skuStockList = jsonArray.toJavaList(SkuStock.class);
                    allSkuStockList.addAll(skuStockList);
                    // 如果返回的数据条数等于每页显示的数量，说明可能还有更多数据，继续查询下一页
                    if (jsonArray.size() == limit) {
                        offset += limit; // 页码增加，指向下一页
                        continue;
                    } else {
                        // 如果返回的数据条数小于每页显示的数量，说明已经查询完所有数据，结束循环
                        break;
                    }
                }
            } else {
                // 如果接口返回的code不是0，表示请求出现问题，这里可以根据实际情况进行错误处理
                System.out.println("请求出现问题，错误信息：" + reponseJson.get("msg"));
                break;
            }

        }

        int batchSize = 100;
        if(!allSkuStockList.isEmpty()){
            QueryWrapper<SkuStock> queryWrapper = new QueryWrapper<>();
            queryWrapper.ge("sku_stock_id", 0);
            skuStockMapper.delete(queryWrapper);
        }
        for (int i = 0; i < allSkuStockList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, allSkuStockList.size());
            List<SkuStock> batchList = allSkuStockList.subList(i, endIndex);
            // 这里可以将batchList用于实际的saveBatch操作或者其他处理
            System.out.println("当前批次数据量: " + batchList.size());
            this.saveBatch(batchList);
            //batchInsert(batchList, batchSize, true);
        }

        System.out.println(allSkuStockList);
        return "";
    }

}